package com.sishu.njrtsdms.manager;

import com.fasterxml.jackson.core.type.TypeReference;
import com.sishu.njrtsdms.constant.cache.CacheConstants;
import com.sishu.njrtsdms.core.RedisCache;
import com.sishu.njrtsdms.domain.vo.DictDataVO;
import com.sishu.njrtsdms.enums.DictDataEnum;
import com.sishu.njrtsdms.exception.ServiceException;
import com.sishu.njrtsdms.jooq.codegen.tables.daos.DictDataDAO;

import org.jooq.types.ULong;
import org.springframework.stereotype.Component;

import java.util.List;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

/**
 * 字典管理器
 */
@Component
@Slf4j
public class DictionaryManager {

    @Resource
    private DictDataDAO dictDataDAO;

    @Resource
    private RedisCache redisCache;



    @PostConstruct
    private void initializeDictDataVOList() {
        var sysDictKey = CacheConstants.SYS_DICT_KEY;
        if (redisCache.hasKey(sysDictKey))
            redisCache.deleteObject(sysDictKey);
        var fetchedDictDataVOList = dictDataDAO.fetchByConditions(null);
        redisCache.setCacheObject(sysDictKey, fetchedDictDataVOList);
    }

    public List<DictDataVO> getDictDataVOList() {
        var sysDictKey = CacheConstants.SYS_DICT_KEY;
        if (!redisCache.hasKey(sysDictKey)) {
            initializeDictDataVOList();
        }
        return redisCache.getCacheList(sysDictKey, new TypeReference<>() {
        });
    }

    public ULong getIdByEnum(DictDataEnum dictDataEnum) {
        List<DictDataVO> dictDataVOS = getDictDataVOList();
        return dictDataVOS.stream()
                .filter(dictDataVO ->
                        dictDataVO.dictType().dictTypeId()
                                .equals(dictDataEnum.getDictTypeId())
                                &&
                                dictDataVO.dictDataValue()
                                        .equals(dictDataEnum.getDictDataValue())
                )
                .findFirst()
                .map(DictDataVO::dictDataId)
                .orElseThrow(() -> {
                    log.error("缓存中不存在对应枚举的字典数据:{}", dictDataEnum);
                    return new ServiceException("系统内部异常");
                });
    }

    public DictDataEnum getEnumById(ULong dictDataId) {
        List<DictDataVO> dictDataVOS = getDictDataVOList();
        return dictDataVOS.stream()
                .filter(dictDataVO ->
                        dictDataVO.dictDataId().equals(dictDataId)
                )
                .findFirst()
                .map(dictDataVO -> DictDataEnum.getEnumByDictTypeIdAndValue(
                        dictDataVO.dictType().dictTypeId(),
                        dictDataVO.dictDataValue()
                ))
                .orElseThrow(() -> {
                    log.error("缓存中不存在此id的字典数据:{}", dictDataId);
                    return new ServiceException("系统内部异常");
                });
    }

}
